<template>
  <div class="goods-image" >
    <!-- 用背景图做放大镜的大图 -->
      <div class="large" :style="[{backgroundImage:`url(${arr[indexs]})`},`background-position: ${bigposition}`] " v-if="!isOutside"></div>
    <div class="middle" ref='target'>
      <img :src='arr[indexs]' alt=""  />
       <div class="layer" v-if="!isOutside" :style="position"></div>
    </div>
    <ul class="small">
      <li v-for="(item, index) in arr" :key="index" @mouseenter="indexs=index" :class="{'active':index===indexs}">
        <img  :src='item' alt="" />

      </li>
    </ul>
  </div>
</template>
<script>
// 组合api用于鼠标移动返回x轴y轴，可以返回在某个元素内部移动的x轴和y轴
import { useMouseInElement } from '@vueuse/core'
import { reactive, ref, watch } from 'vue'
export default {
  props: {
    arr: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    // 大图的移动数据
    const bigposition = ref([null])
    // 小图的移动数据
    const position = reactive({ top: 0, left: 0 })
    const target = ref(null)
    // 接收在ref为target内部移动的x轴y轴和检测鼠标是否在target元素内
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    watch([elementX, elementY], (a, b) => {
      position.left = a[0] - 100
      position.top = a[1] - 100
      if (position.left < 0)position.left = 0
      if (position.top < 0)position.top = 0
      if (position.left > 200)position.left = 200
      if (position.top > 200)position.top = 200
      bigposition.value = (-1 * 2 * position.left) + 'px' + ' ' + (-1 * 2 * position.top) + 'px'

      position.left = position.left + 'px'
      position.top = position.top + 'px'
    }
    )

    const indexs = ref(0)
    return { indexs, elementX, elementY, isOutside, target, position, bigposition }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;

  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
  .layer {
    width: 200px;
    height: 200px;
    background: rgba(0,0,0,.5);
    left: 0;
    top: 0;
    position: absolute;
  }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
